package edu.mse.camel.client.session.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

import edu.mse.camel.client.core.events.model.BaselineResourceUpdate;
import edu.mse.camel.client.eventbus.pubsub.EventManager;
import edu.mse.camel.client.events.EventIDs;
import edu.mse.camel.client.events.peer.SendGenericPeerEvent;
import edu.mse.camel.client.log.Debug;
import edu.mse.camel.client.session.plugin.Activator;

public class FilePublisherUtil {

	public static void publishFiles(List<IFile> selectedFiles) {
		
		for ( IFile file: selectedFiles) {
			
			Debug.log_info(Activator.PLUGIN_ID, "TransferFile : processing file");
			if (file == null || !file.exists()) {
				continue;
			}
			// allocate 16MB buffer
			final int maxFileSize = 16*1024*1024;
			byte [] buf = new byte[maxFileSize];
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			int offset = 0;
			try {
				InputStream in = file.getContents();
				while(in.available()>0) {
						int len = in.read(buf);
						
						if(offset+ len >= maxFileSize) {
							throw new IOException("File size exceeds buffer limit");
						}
						
						out.write(buf, offset, len);
						offset += len;
				}
				
				SendGenericPeerEvent peer = new SendGenericPeerEvent();
				BaselineResourceUpdate update = new BaselineResourceUpdate();

				update.setOriginalFileName(file.getName());
				update.setOriginalProjectName(file.getProject().getName());
				
				update.setFileBuffer(out.toByteArray());
				peer.setSpecificEventId(EventIDs.BASELINE_RESOURCE_UPDATE_EVENT);
				peer.writeObject(update);
				EventManager.getInstance().dispatchEventAsynchronous(peer);

			} catch (CoreException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
				MessageBox errorMsg = new MessageBox(new Shell(), SWT.OK);
				errorMsg.setText("Publish these files");
				errorMsg.setMessage("Error publishing : " + file.getName());
				errorMsg.open();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
				MessageBox errorMsg = new MessageBox(new Shell(), SWT.OK);
				errorMsg.setText("Publish these files");
				errorMsg.setMessage("Error reading : " + file.getName());
				errorMsg.open();
			}
		}		
	}
	
}
